package com.abel.bigwater.wflow.file

import com.aliyun.oss.OSSClient
import com.aliyun.oss.model.PutObjectRequest
import org.apache.catalina.util.URLEncoder
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.io.InputStream

@Component
class AliyunPhotoBucket : PhotoBucket {
    /**
     * 保存照片，并返回full-path without server end-point.
     */
    override fun putPhoto(dirName: String?, photoName: String?, pin: InputStream?): String? {
        if (dirName.isNullOrBlank() || photoName.isNullOrBlank() || pin == null) return null

        val oss = OSSClient(endPoint, accessKeyId, accessKeySecret)

        val key = "$dirName/${System.currentTimeMillis()}~$photoName"
        val po = PutObjectRequest(bucketName, key, pin)
        val por = oss.putObject(po)
        oss.shutdown()

        lgr.info("Put photo: ${por.requestId}")

        return key
    }

    /**
     * 获取照片的URI
     * @param full path of photo but no server end-point.
     */
    override fun visitPhoto(fullPath: String?): String? {
        fullPath ?: return null

        return "$baseUrl/${URLEncoder.DEFAULT.encode(fullPath, Charsets.UTF_8)}"
    }

    companion object {
        private val lgr = LoggerFactory.getLogger(AliyunPhotoBucket::class.java)

        const val endPoint = "https://oss-cn-shenzhen.aliyuncs.com"
        const val baseUrl = "https://bigwater.oss-cn-shenzhen.aliyuncs.com"
        const val bucketName = "bigwater"
        const val accessKeyId = "LTAIzsZOlk6fCA6K"
        const val accessKeySecret = "jMTKDsS6YElJjyqNUkwpRqumFySNet"
    }
}